package com.landinfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.landinfo.service.ViewDataManageService;
import com.landinfo.domain.ViewDataManage;
import com.landinfo.repository.ViewDataManageRepository;
import com.landinfo.service.dto.ViewDataManageDTO;
import com.landinfo.service.mapper.ViewDataManageMapper;
import com.landinfo.web.rest.util.HttpRequestUtil;
import com.landinfo.web.rest.vm.ViewDataManageVM;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Service Implementation for managing ViewDataManage.
 */
@Service
@Transactional
public class ViewDataManageServiceImpl implements ViewDataManageService {

    private final Logger log = LoggerFactory.getLogger(ViewDataManageServiceImpl.class);

    private final ViewDataManageRepository viewDataManageRepository;

    private final ViewDataManageMapper viewDataManageMapper;

    @PersistenceContext
    private EntityManager entityManager;

    public ViewDataManageServiceImpl(ViewDataManageRepository viewDataManageRepository, ViewDataManageMapper viewDataManageMapper) {
        this.viewDataManageRepository = viewDataManageRepository;
        this.viewDataManageMapper = viewDataManageMapper;
    }

    @Override
    public ViewDataManageDTO save(ViewDataManageDTO viewDataManageDTO) {
        ViewDataManage viewDataManage = viewDataManageMapper.toEntity(viewDataManageDTO);
        viewDataManage.setUpdateTime(ZonedDateTime.now());
        viewDataManage = viewDataManageRepository.save(viewDataManage);
        return viewDataManageMapper.toDto(viewDataManage);
    }


    @Override
    @Transactional(readOnly = true)
    public Optional<ViewDataManageDTO> findOne(String id) {
        return viewDataManageRepository.findById(id)
            .map(viewDataManageMapper::toDto);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<ViewDataManageDTO> findByCode(String code) {
        return viewDataManageRepository.findTopByCode(code)
            .map(viewDataManageMapper::toDto);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<ViewDataManageDTO> findByCodeAndPosition(String code, String position) {
        return viewDataManageRepository.findTopByCodeAndPosition(code, position)
            .map(viewDataManageMapper::toDto);
    }

    @Override
    public void delete(String id) {
        viewDataManageRepository.deleteById(id);
    }


    @Override
    public JSONObject queryList(ViewDataManageVM param) {
        JSONObject result = new JSONObject();
        result.put("success", false);
        if (!HttpRequestUtil.checkParamValid(JSON.toJSONString(param))) {
            result.put("msg", "参数错误！");
            return result;
        }
        // 获取查询和统计公共where部分
        String commonWhere = getQuerySql(param);
        if (commonWhere == null) {
            result.put("msg", "无查询权限！");
            return result;
        }
        // 组装统计总数hql
        String countHql = "SELECT COUNT(*) " + commonWhere;
        // 组装查询hql
        StringBuilder sql = new StringBuilder("SELECT * ");
        sql.append(commonWhere);
        if (param.getSort() != null && !param.getSort().equals("")) {
            sql.append(" order by a.").append(param.getSort());
        } else {
            sql.append(" order by a.name");
        }
        Integer count = createNativeCount(countHql);
        List<ViewDataManage> list = new ArrayList<>();
        if (count != null && count > 0) {
            list = createNativeListQuery(sql.toString(), param);
        }
        if (param.getReturnDto() != null && param.getReturnDto().equals("dto2")) {
//            result.put("data", list.stream().map(landProjectManageMapper2::toDto).collect(Collectors.toCollection(LinkedList::new)));
        } else {
            result.put("data", list.stream().map(viewDataManageMapper::toDto).collect(Collectors.toCollection(LinkedList::new)));
        }
        result.replace("success", true);
        result.put("totalElements", count);
        return result;
    }
    private String getQuerySql(ViewDataManageVM param) {
        // 组装其它查询条件
        StringBuilder where = new StringBuilder();
        where.append("1=1");
        if (param.getBigType() != null && !param.getBigType().equals("")) {
            where.append(" and a.big_type = '").append(param.getBigType()).append("'");
        }
        if (param.getName() != null && !param.getName().equals("")) {
            where.append(" and a.name like '%").append(param.getName()).append("%'");
        }
        if (param.getCodeList() != null && param.getCodeList().size() > 0) {
            if (param.getCodeList().size() == 1) {
                where.append(" and a.code = '").append(param.getCodeList().get(0)).append("'");
            } else {
                List<String> codeList = param.getCodeList();
                StringBuilder inSql = new StringBuilder("(");
                for (String s : codeList) {
                    if (!inSql.toString().equals("(")) {
                        inSql.append(",");
                    }
                    inSql.append("'").append(s).append("'");
                }
                inSql.append(")");
                where.append(" and a.code in ").append(inSql);
            }
        }
        if (param.getStartTime() != null && !param.getStartTime().equals("")) {
            where.append(" and a.update_time >= '").append(param.getStartTime()).append("'");
        }
        if (param.getEndTime() != null && !param.getEndTime().equals("")) {
            where.append(" and a.update_time <= '").append(param.getEndTime()).append("'");
        }
        if (param.getKey() != null && !param.getKey().equals("")) {
            where.append(" and (a.name like '%").append(param.getKey()).append("%'");
            where.append(" or a.code like '%").append(param.getKey()).append("%'");
            where.append(" or a.count_config like '%").append(param.getKey()).append("%'");
            where.append(" or a.content like '%").append(param.getKey()).append("%')");
        }
        if (param.getEnable() != null) {
            where.append(" and a.jhi_enable = ").append(param.getEnable());
        }

        // 去掉前部分的 “1=1 and”
        String whereStr = where.toString().replaceFirst("1=1 and", "");
        return String.format("from view_data_manage a where %s", whereStr);
    }
    private List<ViewDataManage> createNativeListQuery(String sql, ViewDataManageVM param) {
        try {
            Query query = entityManager.createNativeQuery(sql, ViewDataManage.class);
            if (param.getPage() != null && param.getSize() != null) {
                query.setFirstResult(param.getPage()*param.getSize());
                query.setMaxResults(param.getSize());
            }
            return query.getResultList();
        } catch (Exception e) {
            System.out.println("查询出错：" + e.getMessage());
            return new ArrayList<>();
        }
    }
    private Integer createNativeCount(String sql) {
        try {
            Query query = entityManager.createNativeQuery(sql);
            Integer count = Integer.parseInt(query.getSingleResult().toString());
            return count;
        } catch (Exception e) {
            System.out.println("查询出错：" + e.getMessage());
            return null;
        }
    }

}
